package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.auth.utils.JwtUtils;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;


@Slf4j
@Configuration
@EnableConfigurationProperties(ClientProperties.class)
@ConditionalOnProperty(prefix = "ly.auth", name = {"clientId", "secret"})//意思是环境中必须有`ly.auth`开头的属性，名称必须叫`clientId`和`secret`，确保使用者会在yml中配置clientId和secret时，当前配置才会生效
@EnableFeignClients(basePackages = "com.leyou.auth.client")//引入AuthClient
public class AuthConfiguration {

    @Autowired
    private AuthClient authClient;
    @Autowired
    private ClientProperties properties;

    //完成秘钥加载，并完成对JwtUtils的初始化
    @Bean
    @Primary
    public JwtUtils jwtUtils() throws InterruptedException {
        // 向ly-auth发送请求，申请秘钥
        while (true){
            try {
                // 查询秘钥
                String key = authClient.getSecretKey(properties.getClientId(), properties.getSecret());
                // 创建JwtUtils
                JwtUtils jwtUtils = new JwtUtils(key);
                log.info("获取秘钥成功。");
                //System.out.println("秘钥加载成功。");
                return jwtUtils;
            } catch (FeignException e) {
                // 加载秘钥失败，5秒后重试
                log.error("加载jwt秘钥失败了!原因： {}", e.contentUTF8());
                Thread.sleep(5000);
            }
        }
    }
}